from rest_framework.generics import GenericAPIView
from meiduo_admin.serializer.spec_serializer import *
from goods.models import *
from meiduo_admin.pages import MyPage
from rest_framework.response import Response


# 请求方式： GET /meiduo_admin/goods/specs/
class SpecsView(GenericAPIView):
    serializer_class = SPUSpecificationSerializer
    queryset = SPUSpecification.objects.all()
    pagination_class = MyPage

    """获取规格数据表"""
    def get(self, request):
        spec = self.get_queryset()
        page = self.paginate_queryset(spec)
        if page:
            page_serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(page_serializer.data)
        serializer = SPUSpecificationSerializer(spec, many=True)
        return Response(serializer.data)

    """保存规格"""
    def post(self, request):
        spec = self.request.data
        print(spec)
        serializer = SPUSpecificationSerializer(data=spec)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=201)


# 请求方式： GET /meiduo_admin/goods/specs/(?P<pk>\d+)/
class SpecsSingleView(GenericAPIView):
    serializer_class = SPUSpecificationSerializer
    queryset = SPUSpecification.objects.all()

    """获取规格单一数据"""
    def get(self, request, pk):
        spec_obj = SPUSpecification.objects.get(pk=pk)
        serializer = SPUSpecificationSerializer(spec_obj)
        return Response(serializer.data)

    """修改"""
    def put(self, request, pk):
        spec_obj = self.get_object()
        serializer = SPUSpecificationSerializer(instance=spec_obj, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    """删除"""
    def delete(self, request, pk):
        spec = self.get_object()
        spec_obj = spec.delete()
        return Response(spec_obj)